package com.thfw.test.view.fragment;

import android.app.AlertDialog;
import android.app.TimePickerDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.Toast;

import com.bigkoo.pickerview.TimePickerView;
import com.google.gson.Gson;
import com.kyleduo.switchbutton.SwitchButton;
import com.thfw.wmd.R;
import com.thfw.test.model.authManage.AuthBaseBean;
import com.thfw.test.model.authManage.TokenBean;
import com.thfw.test.model.bean.BindingBean;
import com.thfw.test.model.bean.CaptchaBean;
import com.thfw.test.model.bean.GroupBean;
import com.thfw.test.model.bean.MainMsgBean;
import com.thfw.test.model.bean.RegionBean;
import com.thfw.test.utils.ConfigurationEntry;
import com.thfw.test.utils.StringUtils;
import com.thfw.test.view.activity.LoginActivity;
import com.thfw.test.view.activity.MainActivity;
import com.thfw.test.view.network.AuthManageService;
import com.thfw.test.view.widget.AmountView;
import com.thfw.test.view.widget.TouchProgessView;

import org.json.JSONException;
import org.json.JSONObject;

import java.net.MalformedURLException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.TreeMap;
import java.util.stream.Collectors;

import butterknife.BindView;
import okhttp3.MediaType;
import okhttp3.RequestBody;
import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import scooper.cn.sc_base.AppActivities;
import scooper.cn.sc_base.log.SCLog;
import utils.CollectionUtils;
import utils.PasswordUtils;
import utils.RetrofitWrapper;

import static com.thfw.test.model.bean.RegionBean.prinfAllRegion;

/**
 * Created BY Cuishikun
 * Created ON 2021/11/12
 * Package Name com.thfw.test.view.fragment
 **/
public class LightControlFragment extends BaseFragment {
    private static final String TAG = LightControlFragment.class.getCanonicalName();
    @BindView(R.id.view_pg)
    TouchProgessView view_pg;
    @BindView(R.id.top_buttons)
    protected RadioGroup topButtons;
    @BindView(R.id.btn_select_group)
    Spinner btn_select_group;
    @BindView(R.id.view_sw_light)
    SwitchButton view_sw_light;
    @BindView(R.id.btn_save)
    TextView btn_save;
    @BindView(R.id.tv_nowregion)
    TextView tv_nowregion;
    @BindView(R.id.view_sw_sensor)
    SwitchButton view_sw_sensor;
    @BindView(R.id.view_sw_schedul)
    SwitchButton view_sw_schedul;
    @BindView(R.id.ed_time1)
    EditText ed_time1;
    @BindView(R.id.ed_time2)
    EditText ed_time2;

    @BindView(R.id.av_light_on)
    AmountView av_light_on;
    @BindView(R.id.av_light_off)
    AmountView av_light_off;
    @BindView(R.id.ib_schdul_time)
    TextView ib_schdul_time;
    @BindView(R.id.ib_opentime)
    Button ib_opentime;
    @BindView(R.id.ib_closetime)
    Button ib_closetime;
    @BindView(R.id.tv_all)
    TextView tv_all;
    @BindView(R.id.tv_online)
    TextView tv_online;
    @BindView(R.id.tv_today_energy)
    TextView tv_today_energy;
    boolean selectAll = true;
    ArrayAdapter<String> arr_adapter;

    private RegionBean nowRegion;
    private ArrayList<RegionBean> nowRegionList;
    private AlertDialog alertDialog2; //单选框
    private AlertDialog alertDialog3; //多选框
    private TimePicker timeDialog;
    private TreeMap<String, Integer> map;
    ArrayList<Integer> timeList;
    private GroupBean nowGroup;
    int port;
    String host;
    public static LightControlFragment newInstance() {
        LightControlFragment fragment = new LightControlFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected int getLayoutResource() {
        return R.layout.fm_lightcontrol;
    }

    @Override
    protected void initView() {

        host = getConfig().getString(ConfigurationEntry.HOST, "192.168.161.121");
        port = getConfig().getInt(ConfigurationEntry.PORT, 8080);

        //设置progress与viewpager滑动冲突问题
        view_pg.setOnTouchListener((v, event) -> {
            view_pg.getParent().requestDisallowInterceptTouchEvent(true);
            return false;
        });
        view_pg.setOnProgressChangedListener(new TouchProgessView.OnProgressChangedListener() {
            @Override
            public void onProgressChanged(View view, int progress) {

            }

            @Override
            public void onProgressSuccess(View view, int progress) {
                Toast.makeText(getActivity(), "当前亮度已调节为" + progress, Toast.LENGTH_SHORT).show();
                brightnessAll(progress);
            }
        });
        ib_schdul_time.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showMutilAlertDialog();
            }
        });
        topButtons.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {

                if (checkedId == R.id.all_talks) {
                    btn_select_group.setVisibility(View.VISIBLE);
                    selectAll = false;
                } else if (checkedId == R.id.missed_call) {
                    btn_select_group.setVisibility(View.GONE);
                    selectAll = true;
                }
            }
        });
        //监听全局灯控开关
        view_sw_light.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    lightOpenAll(0);
                } else {
                    lightOpenAll(1);
                }
            }
        });
        btn_save.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                add4TimeAndMan();
            }
        });
        tv_nowregion.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (nowRegionList != null) {
                    showSingleAlertDialog(nowRegionList);
                } else {
                    getRegion();
                }
            }
        });
        ib_opentime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePick(ib_opentime);
            }
        });

        ib_closetime.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                showTimePick(ib_closetime);
            }
        });
        getMainMsg();

    }

    @Override
    protected void firstCreate() {
        //获取区域地块
        map = new TreeMap<>();
        timeList = new ArrayList<>();
        getRegion();
    }


    private void getGroupData() {
        try {

            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");
            Map<String, String> params = new HashMap<>();
            if (nowRegion != null) {
                params.put("regionId", nowRegion.getValue());
            }
            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).getLightGroupNew(token, params).enqueue(new Callback<AuthBaseBean<ArrayList<GroupBean>>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<ArrayList<GroupBean>>> call, Response<AuthBaseBean<ArrayList<GroupBean>>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());
                    ArrayList<String> list = new ArrayList<>();
                    if (response != null && response.body() != null && response.body().getData() != null) {
                        for (GroupBean bean : response.body().getData()) {
                            list.add(bean.getGroupName());
                        }
                        //适配器
                        arr_adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_item, list);
                        //设置样式
                        arr_adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
                        //加载适配器
                        btn_select_group.setAdapter(arr_adapter);

                        btn_select_group.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
                            @Override
                            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                                if (response.body().getData() != null && response.body().getData().size() != 0) {
                                    nowGroup = response.body().getData().get(position);
                                }
                            }

                            @Override
                            public void onNothingSelected(AdapterView<?> parent) {

                            }
                        });
                    }


                }

                @Override
                public void onFailure(Call<AuthBaseBean<ArrayList<GroupBean>>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());

                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    //控制灯光打开关闭
    private void lightOpenAll(int isOpen) {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");
            Map<String, String> params = new HashMap<>();
            if (selectAll) {
                params.put("regionId", nowRegion.getValue());
            } else {
                params.put("groupId", nowGroup.getGroupId());
            }
            params.put("isOpen", isOpen + "");

            RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json;"),
                    new JSONObject(params).toString());

            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).lightOpenAll(token, requestBody).enqueue(new Callback<AuthBaseBean<Object>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<Object>> call, Response<AuthBaseBean<Object>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());
                    Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<AuthBaseBean<Object>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());
                    Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();

                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    //控制灯光亮度
    private void brightnessAll(int level) {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");
            Map<String, String> params = new HashMap<String, String>();
            if (selectAll) {
                params.put("regionId", nowRegion.getValue() + "");
            } else {
                params.put("groupId", nowGroup.getGroupId() + "");
            }
            params.put("light", level + "");

            RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json;"),
                    new JSONObject(params).toString());

            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).brightnessAll(token, requestBody).enqueue(new Callback<AuthBaseBean<Object>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<Object>> call, Response<AuthBaseBean<Object>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());
                    Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<AuthBaseBean<Object>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());
                    Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    //设置生效策略

    private void add4TimeAndMan() {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");
            BindingBean parms = new BindingBean();
            parms.setBindingState(getBingdingState());
            parms.setManState(getmanState());
            parms.setRegionId(nowRegion.getValue());
            parms.setGrpId(getGroupId());
            parms.setType(getType());
            parms.setMan(getMan());
            parms.setTime(getTime());
            RequestBody requestBody = RequestBody.create(MediaType.parse("Content-Type, application/json;"),
                    new Gson().toJson(parms));

            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).add4TimeAndMan(token, requestBody).enqueue(new Callback<AuthBaseBean<BindingBean>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<BindingBean>> call, Response<AuthBaseBean<BindingBean>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());
                    Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();
                }

                @Override
                public void onFailure(Call<AuthBaseBean<BindingBean>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());
                    Toast.makeText(getActivity(), "操作失败", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    //获取首页信息
    private void getMainMsg() {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");

            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).getMainMsg(token).enqueue(new Callback<AuthBaseBean<MainMsgBean>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<MainMsgBean>> call, Response<AuthBaseBean<MainMsgBean>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());
                    //设备总数
                    if (response != null && response.body() != null && response.body().getData() != null
                            && response.body().getData().getOverview() != null) {
                        tv_all.setText(response.body().getData().getOverview().getLampAllNum() + "");
                        //能耗
                        tv_today_energy.setText(response.body().getData().getOverview().getLampEnergy() + "KW");
                        getConfig().putString(ConfigurationEntry.TODAY_ENERGY, response.body().getData().getOverview().getLampEnergy() + "KW", true);
                        //在线设备
                        tv_online.setText(response.body().getData().getOverview().getLampType().getLampType() + "");
                    } else {
                        Toast.makeText(getActivity(), response.message(), Toast.LENGTH_SHORT).show();

                    }
                }

                @Override
                public void onFailure(Call<AuthBaseBean<MainMsgBean>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());
                    Toast.makeText(getActivity(), "获取首页信息失败", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }

    //区域选择提示

    private void getRegion() {
        try {
            String url = StringUtils.buildURL("http", host, port, "", null).toString();
            String token = getConfig().getString(ConfigurationEntry.TOKEN, "");

            RetrofitWrapper.getInstance(getActivity(), url).create(AuthManageService.class).getRegion(token).enqueue(new Callback<AuthBaseBean<ArrayList<RegionBean>>>() {
                @Override
                public void onResponse(Call<AuthBaseBean<ArrayList<RegionBean>>> call, Response<AuthBaseBean<ArrayList<RegionBean>>> response) {
                    SCLog.e(TAG, "response is onResponse" + call.toString());
                    if (response != null && response.body() != null && response.body().getData() != null) {
                        ArrayList<RegionBean> list = new ArrayList<>();
                        for (RegionBean bean : response.body().getData()) {
                            list.addAll(prinfAllRegion(bean));
                        }
                        nowRegionList = list;
                        if (nowRegion == null) {
                            showSingleAlertDialog(list);
                        }
                    } else {
                        Toast.makeText(getActivity(), "获取区域信息失败", Toast.LENGTH_SHORT).show();
                    }

                }

                @Override
                public void onFailure(Call<AuthBaseBean<ArrayList<RegionBean>>> call, Throwable t) {
                    SCLog.e(TAG, "response is onFailure" + call.toString());
                    Toast.makeText(getActivity(), "获取区域信息失败", Toast.LENGTH_SHORT).show();
                }
            });
        } catch (MalformedURLException e) {
            e.printStackTrace();
        }
    }


    public void showSingleAlertDialog(ArrayList<RegionBean> list) {
        String[] items = new String[list.size()];
        for (int i = 0; i < list.size(); i++) {
            items[i] = list.get(i).getLabel();
        }
        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle("请选择要控制的区域");
        alertBuilder.setSingleChoiceItems(items, 0, new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                nowRegion = list.get(i);
                tv_nowregion.setText(nowRegion.getLabel());
            }
        });

        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog2.dismiss();
                if (nowRegion != null && nowRegion.getLabel() != null) {
                    tv_nowregion.setText(nowRegion.getLabel());
                }
                getGroupData();
            }
        });

//        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
//            @Override
//            public void onClick(DialogInterface dialogInterface, int i) {
//                alertDialog2.dismiss();
//
//            }
//        });

        alertDialog2 = alertBuilder.create();
        alertDialog2.setCanceledOnTouchOutside(false);
        alertDialog2.show();
    }

    //定时策略
    private int getBingdingState() {
        if (view_sw_schedul.isFadeBack()) {
            return 1;
        } else {
            return 0;
        }


    }

    //人感策略
    private int getmanState() {
        if (view_sw_sensor.isFadeBack()) {
            return 1;
        } else {
            return 0;
        }
    }

    //获取区域还是组控制

    private int getType() {
        if (selectAll) {
            return 0;
        } else {
            return 1;
        }
    }

    //获取组id
    private String getGroupId() {
        if (selectAll) {
            return null;
        } else {
            return btn_select_group.getTransitionName();
        }
    }

    //获取策略
    private BindingBean.Man getMan() {
        BindingBean.Man man = new BindingBean.Man();
        man.setDelayTime(Integer.valueOf(getText(ed_time1)));
        man.setChangeNot(Integer.valueOf(getText(ed_time2)));
        man.setMaxManLight(Integer.valueOf(av_light_on.getEtAmount())*5);
        man.setMinManLight(Integer.valueOf(av_light_off.getEtAmount())*5);
        return man;
    }


    public String getText(EditText ed) {
        if (ed.getText().equals("")) {
            return "0";
        } else {
            return ed.getText().toString();
        }
    }

    private BindingBean.Time getTime() {
        BindingBean.Time man = new BindingBean.Time();
        timeList = new ArrayList<>();
        if (!ib_schdul_time.getText().equals("")) {
            String[] items = ib_schdul_time.getText().toString().split(",");
            for (String s : items) {
                timeList.add(Integer.valueOf(s));
            }
        }
        man.setWeeks(timeList);
        man.setOpenTime(ib_opentime.getText().toString());
        man.setShutTime(ib_closetime.getText().toString());
        man.setLight(view_pg.getProgressNum());
        return man;
    }

    boolean[] selecteditems = {true, true, true, false, false, false, false};

    //多选框
    public void showMutilAlertDialog() {
        final String[] items = {"星期一", "星期二", "星期三", "星期四", "星期五", "星期六", "星期日"};

        AlertDialog.Builder alertBuilder = new AlertDialog.Builder(getActivity());
        alertBuilder.setTitle("请选择生效日期");
        /**
         *第一个参数:弹出框的消息集合，一般为字符串集合
         * 第二个参数：默认被选中的，布尔类数组
         * 第三个参数：勾选事件监听
         */
        alertBuilder.setMultiChoiceItems(items, selecteditems, new DialogInterface.OnMultiChoiceClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i, boolean isChecked) {
                if (isChecked) {
                    selecteditems[i] = true;
                } else {
                    selecteditems[i] = false;
                }
            }
        });
        alertBuilder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog3.dismiss();
                StringBuilder s = new StringBuilder();
                for (int j = 0; j < 7; j++) {
                    if (selecteditems[j]) {
                        if (s.length() != 0) {
                            s.append(",");
                            s.append(j + 1);
                        } else {
                            s.append(j + 1);
                        }
                    }
                }

                ib_schdul_time.setText(s.toString());
            }
        });

        alertBuilder.setNegativeButton("取消", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                alertDialog3.dismiss();
            }
        });


        alertDialog3 = alertBuilder.create();
        alertDialog3.show();


    }


    private void showTimePick(Button btn) {


        TimePickerView pvTime = new TimePickerView.Builder(getActivity(), new TimePickerView.OnTimeSelectListener() {
            @Override
            public void onTimeSelect(Date date, View v) {
                SimpleDateFormat formatter = new SimpleDateFormat("HH:mm:ss");
                String datef = formatter.format(date);
                btn.setText(datef);
            }
        })
                .setType(new boolean[]{false, false, false, true, true, true})// 默认全部显示
                .setCancelText("取消")//取消按钮文字
                .setSubmitText("确定")//确认按钮文字

                .isCenterLabel(false) //是否只显示中间选中项的label文字，false则每项item全部都带有label。
                .build();

        pvTime.show();

    }
}
